import store from '@/store'
import { isArray } from '@/utils/is.js'

function checkPermission(el, binding) {
  const roles = store.getters && store.getters['user/roles']
  const { value } = binding
  if (!isArray(value)) throw new Error('need roles! Like v-permission=[1,2]')
  if (value.length > 0) {
    const hasPermission = roles.some(role => {
      return value.includes(role)
    })
    if (!hasPermission) {
      // 没有权限--移除该元素
      el.parentNode && el.parentNode.removeChild(el)
    }
  }
}

export default {
  inserted(el, binding) {
    checkPermission(el, binding)
  },
  update(el, binding) {
    checkPermission(el, binding)
  }
}
